package test.lrucache;

import java.util.LinkedHashMap;
import java.util.Map;

public class LRUCache {

    private Map<Integer, Integer> cache;

    private int capacity;

    private int size;

    public LRUCache(int capacity) {
        cache = new LinkedHashMap<>(capacity);
        this.capacity = capacity;
        this.size = 0;
    }

    public int get(int key) {
        Integer v = cache.remove(key);
        if (v == null) {
            return -1;
        }
        cache.put(key, v);
        return v;
    }

    public void put(int key, int value) {
        Integer old = cache.remove(key);
        if (old==null) {
            if (size >= capacity) {
                Integer useless = cache.keySet().iterator().next();
                cache.remove(useless);
            } else {
                size++;
            }
        }
        cache.put(key, value);

    }
}